package com.hh.aspect;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hh.anno.Log;
import com.hh.entity.SysLog;
import com.hh.entity.SysUser;
import com.hh.service.SysLogService;
import com.hh.service.SysUserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 辉辉 2022/8/16 8:40
 */
@Aspect
@Component
public class LogAspect {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysLogService sysLogService;

    /**
     * 切面
     * @param joinPoint
     * @return
     */
    @Around(value = "@annotation(com.hh.anno.Log)")
    public Object myLogAspect(ProceedingJoinPoint joinPoint) {
        // 记录用户的操作
        Object result = null;
        // 拿到方法名称 方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        // 拿到注解
        Log log = signature.getMethod().getAnnotation(Log.class);
        // 拿到属性
        String operation = log.operation();
        // 拿到方法执行时间
        long start = System.currentTimeMillis();
        // 执行方法
        try {
            result = joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 拿到响应时间
        long end = System.currentTimeMillis();
        // 拿到当前用户名称
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        // 查询当前用户根据用户ID
//        sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId, Long.valueOf(userId)));
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().select(SysUser::getUsername).eq(SysUser::getUserId, Long.valueOf(userId)));
        String username = sysUser.getUsername();
        // 拿到ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        // 组装对象
        SysLog sysLog = SysLog.builder()
                .username(username)
                .ip(ip)
                .params(joinPoint.getArgs() == null ? "" : JSON.toJSONString(joinPoint.getArgs()))
                .operation(operation)
                .time(end - start)
                .createDate(new Date())
                .build();
        // 插入数据库
        sysLogService.save(sysLog);
        return result;
    }
}
